package com.jxcq.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @author CalvinXCui
 * @date 2019- 10- 18 15:06
 */
@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在请求前(pre)或者后(post)执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器执行顺序，数字越小，表示越先执行
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否开启  true表示开启  false表示关闭
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器内执行的操作   return任何object的值都表示放行
     * setsendzullrespponse(false)表示不在继续执行
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("经过后台过滤器了");
        RequestContext requestContext = RequestContext.getCurrentContext();//得到上下文
        HttpServletRequest request = requestContext.getRequest();//得到request域

        if(StringUtils.equals("OPTIONS",request.getMethod())){//第一次分发请求时，直接放行
            return null;
        }

        if(request.getRequestURI().indexOf("login")>0){//关于登录时也直接放行
            return null;
        }

        System.out.println(request.getMethod());
        System.out.println(request.getRequestURI());

        String headers = request.getHeader("Authorization");//获取头信息
        if(StringUtils.isNotEmpty(headers) && headers.startsWith("Bearer ")){
            String token = headers.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                String role = (String)claims.get("role");
                if(StringUtils.equals("admin",role)){
                    //把信息转发并且放行
                    requestContext.addZuulRequestHeader("Authorization",headers);
                    return null;
                }
            }catch (Exception e){
                e.printStackTrace();
                requestContext.setSendZuulResponse(false);//终止运行
            }
        }
        requestContext.setSendZuulResponse(false);//终止运行
        requestContext.setResponseStatusCode(403);
        requestContext.setResponseBody("权限不足");
        requestContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
